<template>
    <header :class="isScroll&&'sticky'">
      <router-link to="/" class="logo"><img src="@/assets/images/logo.png" alt=""></router-link>
      <ul class="nav">
        <li v-for="(item,index) in menus.children" :key="index">
          <a href="javascript:;" target="_self" class="m" v-if="item.path=='/recruit'" @click="checkAuth">{{item.meta.title}}</a>
          <router-link class="m" v-else :to="item.path">{{item.meta.title}}</router-link>
          <template v-if="item.children">
            <dl>
              <dd v-if="!sub.meta.isHide" v-for="(sub,index2) in item.children" :key="index2">
                <router-link :to="sub.path">{{sub.meta.title}}</router-link>
              </dd>            
            </dl>
          </template>
        </li>
      </ul>
      <div class="fr">
        <ul>
          <li class="ico_service">
            <div href="javascript:;" target="_self" class="ico_service"></div>
            <dl>
              <dd v-if="!item.meta.isHide" v-for="(item,index) in servicerMenus.children" :key="index">
                  <a href="javascript:;" target="_self" v-if="item.path=='/service/QNA'" @click="checkAuth2">{{item.meta.title}}</a>
                  <router-link v-else :to="item.path">{{item.meta.title}}</router-link>
              </dd>            
            </dl>
          </li>
          <li class="line"></li>
          <li v-if="userInfo">
            <router-link to="/my/job" class="ico_user" v-if="role=='enterprise'"></router-link>
            <router-link to="/my" class="ico_user" v-else></router-link>
            <dl>
              <dd v-if="isShow(item.meta.roles)&&!item.meta.isHide" v-for="(item,index) in userMenus.children" :key="index">
                <a href="javascript:;" target="_self" v-if="item.path=='/my/check'" @click="checkLoginType(item.path)">{{item.meta.title}}</a>
                <router-link v-else :to="item.path">{{item.meta.title}}</router-link> 
              </dd>
              <dd><a href="javascript:;" target="_self" @click="logout">로그아웃</a></dd>
            </dl>
          </li>
          <li v-if="!userInfo">
            <a href="javascript:;" target="_self" class="btn">로그인</a>
            <dl>
              <dd><router-link to="/login">개인회원</router-link></dd>
              <dd><router-link to="/login?userType=enterprise">기업회원</router-link></dd>
            </dl>
          </li>
          <li v-if="!userInfo">
            <a href="javascript:;" target="_self" class="btn">회원가입</a>
            <dl>         
              <dd><router-link to="/register">개인회원</router-link></dd>
              <dd><router-link to="/registerEnt">기업회원</router-link></dd>            
            </dl>
          </li>
        </ul>
      </div>
      <div :class="['wap',drawer&&'open']">
        <div class="navBtn" @click="showNav">
            <div class="icon"><div class="line"></div></div>
        </div>
        <transition name="slide-fade">
          <div class="mask" v-if="drawer" @click="drawer=false"></div>
          <div class="mask2" v-if="userNav||logNav||regNav" @click="closeAllNav"></div>
        </transition>  
        <div class="navBox">
            <ul>
              <li v-for="(item,index) in wapNav" :key="index">
                <div class="parent">
                  <a href="javascript:;" target="_self" class="m" v-if="item.path=='/recruit'" @click="checkAuth">{{item.meta.title}}</a>
                  <router-link class="m" v-else :to="item.path">{{item.meta.title}}</router-link>
                  <div :class="['arrow',item.isOpen&&'open']" v-if="item.children" @click="openNav(index,item.isOpen)">
                    <i class="el-icon-caret-bottom"></i>
                  </div>	
                </div>
                <template v-if="item.children">
                  <div class="sub" v-show="item.isOpen">
                    <div class="item" v-if="!sub.meta.isHide" v-for="(sub,index2) in item.children" :key="index2">
                      <a href="javascript:;" target="_self" v-if="sub.path=='/service/QNA'" @click="checkAuth2">{{sub.meta.title}}</a>
                      <router-link v-else :to="sub.path">{{sub.meta.title}}</router-link>
                    </div>            
                  </div>
                </template>
              </li>              
            </ul>
        </div>
        <div class="userBox">
          <ul>
            <li v-if="userInfo">
              <div class="parent" @click="showUserNav">
                <span class="ico_user"></span>
              </div>
              <div class="sub" v-if="userNav">
                <div class="item" v-if="isShow(item.meta.roles)&&!item.meta.isHide" v-for="(item,index) in userMenus.children" :key="index">
                  <a href="javascript:;" target="_self" v-if="item.path=='/my/check'" @click="checkLoginType(item.path)">{{item.meta.title}}</a>
                  <router-link v-else :to="item.path">{{item.meta.title}}</router-link>                  
                </div>
                <div class="item"><a href="javascript:;" target="_self" @click="logout">로그아웃</a></div>
              </div>
            </li>
            <li v-if="!userInfo">
              <div class="parent" @click="showLogNav">
                <a href="javascript:;" target="_self">로그인</a>
              </div>              
              <div class="sub" v-if="logNav">
                <div class="item"><router-link to="/login">개인회원</router-link></div>
                <div class="item"><router-link to="/login?userType=enterprise">기업회원</router-link></div>
              </div>
            </li>
            <li v-if="!userInfo">
              <div class="parent" @click="showRegNav">
                <a href="javascript:;" target="_self">회원가입</a>
              </div>
              <div class="sub" v-if="regNav">
                <div class="item"><router-link to="/register">개인회원</router-link></div>
                <div class="item"><router-link to="/registerEnt">기업회원</router-link></div>            
              </div>
            </li>
          </ul>
        </div>
      </div>
    </header>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import menuRoutes from '@/router/modules/menu'
import userRoutes from '@/router/modules/user'
import serviceRoutes from '@/router/modules/service'
import { getToken } from '@/utils/auth'
import { Local } from '@/utils'
import { getUserInfo } from '@/api'

export default {
  name: 'layoutHeader',
  components: {},
  props: [],
  data () {
    return {
      menus: menuRoutes,
      userMenus: userRoutes,
      servicerMenus: serviceRoutes,
      isScroll: false,
      drawer: false,
      userNav: false,
      logNav: false,
      regNav: false,
      wapNav: []
    }
  },
  computed: {
    ...mapState(['userInfo', 'role', 'anchor'])
  },
  created () {
    let _token = getToken(), _type = Local.get('ust'), _email = Local.get('email'), _regDate = Local.get('regDate'), _userInfo = Local.get('userInfo');
    _token && this.setUserToken(_token)
    if (_userInfo) {
      let _type = 'personal'
      if (_userInfo.member_type == 2) {
        _type = 'enterprise'
      }
      this.setRole(_type);
      Local.set('ust', _type);
      this.$store.dispatch('setAccessRoutes')
    }
    _regDate && this.setRegDate(_regDate)
    _email && this.setEmail(_email)
    if (_token) {
      !_userInfo ? this.getUserInfo() : this.setUserInfo(_userInfo)
    }
    this.setWapNav()
  },
  mounted () {
    window.addEventListener('scroll', this.getScroll);
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.getScroll)
  },
  methods: {
    ...mapActions(['setUserToken', 'setRole', 'setEmail', 'setUserInfo', 'setAnchor', 'setRegDate']),
    async logout () {
      await this.$store.dispatch('logout')
      window.location.href = window.location.origin
      // this.$router.push({ path: '/' })
    },
    async getUserInfo () {
      let res = await getUserInfo();
      if (res.code == 200) {
        this.setUserInfo(res.data)
        Local.set('userInfo', res.data)
      }
    },
    setWapNav () {
      let _nav = [], _new = [];
      _new = _nav.concat(menuRoutes.children, serviceRoutes);
      _new.forEach(item => {
        item.isOpen = false
      });
      this.wapNav = JSON.parse(JSON.stringify(_new))
    },
    openNav (index, isOpen) {
      this.wapNav[index].isOpen = !isOpen
    },
    openPage (path, tag) {
      let _path = this.$route.path;
      this.setAnchor(tag);
      if (_path != path) {
        this.$router.push({ path: path })
      }
    },
    isShow (roles) {
      return roles.indexOf(this.role) > -1
    },
    getScroll () {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      if (!!document.documentElement.scrollTop && document.documentElement.scrollTop >= 10) {
        this.isScroll = true
      } else {
        this.isScroll = false
      }
    },
    showNav () {
      this.drawer = true;
      this.closeAllNav()
    },
    closeAllNav () {
      this.userNav = false
      this.logNav = false
      this.regNav = false
    },
    showUserNav () {
      this.userNav = !this.userNav;
    },
    showLogNav () {
      this.logNav = !this.logNav
      this.regNav = false
    },
    showRegNav () {
      this.regNav = !this.regNav
      this.logNav = false
    },
    checkAuth () {
      if (this.userInfo && this.userInfo.member_type == 2) {
        this.$router.push('/recruit')
      } else {
        this.$confirm('인재를 찾고 계신가요?<br/>워크위즈 기업회원을 위한 서비스입니다.<br/>아직 회원이 아니시라면, [기업회원]가입 인재를 찾아보세요!', '알림', {
          dangerouslyUseHTMLString: true,
          cancelButtonText: '닫기',
          confirmButtonText: '기업회원 가입',
        }).then(() => {
          if (this.userInfo) {
            this.confirmTwo();
          } else {
            this.$router.push('/login?userType=enterprise')
          }
        })
      }
    },
    confirmTwo () {
      this.$confirm('사용 중인 계정 로그아웃 후 기업회원을 가입해 주세요.', '알림', {
        cancelButtonText: '취소',
        confirmButtonText: '로그아웃',
      }).then(async () => {
        await this.$store.dispatch('logout')
        this.$router.push({ path: '/registerEnt' })
      })
    },
    checkAuth2 () {
      if (this.userInfo) {
        this.$router.push('/service/QNA')
      } else {
        this.$alert('로그인 사용자만 확인이 가능합니다.', '알림', {
          confirmButtonText: '확인'
        })
      }
    },
    checkLoginType (path) {
      if (this.userInfo && this.userInfo.login_type == 1) {
        if (this.userInfo.member_type == 2) {
          this.$router.replace('/my/enterprise')
        } else {
          this.$router.replace('/my/personal')
        }
      } else {
        this.$router.push(path)
      }
    }
  },
  watch: {
    $route (to, from) {
      this.drawer = false
      this.closeAllNav()
    }
  }
}
</script>